<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getServiceList, getServiceDetail, updateServiceStatus, replyToService } from '@/api/service'
import { getImageUrl } from '@/api/file'

// 服务请求列表数据
const serviceList = ref([])

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 搜索条件
const searchForm = reactive({
  keyword: '',
  type: null,
  status: null
})

// 回复对话框
const replyDialogVisible = ref(false)
const currentService = ref(null)
const replyContent = ref('')

// 图片预览相关
const previewImages = ref([])
const previewVisible = ref(false)
const previewIndex = ref(0)

// 加载服务请求列表
const loadServiceList = async () => {
  try {
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize,
      keyword: searchForm.keyword,
      type: searchForm.type,
      status: searchForm.status
    }
    
    console.log('API请求参数:', params)
    const res = await getServiceList(params)
    console.log('API响应结果:', res)
    
    if (res.code === 200) {
    
      serviceList.value = res.data.records || []
      pagination.total = res.data.total || 0
    } else {
      ElMessage.error(res.message || '获取服务请求列表失败')
    }
  } catch (error) {
    console.error('获取服务请求列表出错', error)
    ElMessage.error('获取服务请求列表失败，请稍后重试')
  }
}

// 处理搜索
const handleSearch = () => {
  pagination.currentPage = 1
  console.log('搜索条件:', searchForm)
  loadServiceList()
}

// 处理重置
const handleReset = () => {
  searchForm.keyword = ''
  searchForm.type = null
  searchForm.status = null
  pagination.currentPage = 1
  loadServiceList()
}

// 处理分页变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  loadServiceList()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  loadServiceList()
}

// 查看服务请求详情
const handleDetail = async (row) => {
  try {
    const res = await getServiceDetail(row.id)
    if (res.code === 200) {
      const service = res.data
      
      ElMessageBox.alert(
        `
        <p><strong>类型：</strong>${formatType(service.type)}</p>
        <p><strong>状态：</strong>${formatStatus(service.status)}</p>
        <p><strong>提交时间：</strong>${service.createTime}</p>
        <p><strong>提交人：</strong>${service.username}</p>
        <p><strong>联系电话：</strong>${service.phone || '无'}</p>
        <p><strong>服务地址：</strong>${service.address || '无'}</p>
        <p><strong>描述：</strong>${service.content}</p>
        ${service.images ? `<p><strong>图片：</strong><br/><div style="margin-top: 10px;">${formatImages(service.images)}</div></p>` : ''}
        ${service.reply ? `<p><strong>回复：</strong>${service.reply}</p><p><strong>回复时间：</strong>${service.replyTime}</p>` : '<p><strong>回复：</strong>暂无回复</p>'}
        `,
        '服务请求详情',
        {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定',
          callback: () => {}
        }
      )
    } else {
      ElMessage.error(res.message || '获取服务请求详情失败')
    }
  } catch (error) {
    console.error('获取服务请求详情出错', error)
    ElMessage.error('获取服务请求详情失败，请稍后重试')
  }
}

// 处理服务请求状态更新
const handleStatusChange = async (row, status) => {
  const statusMap = {
    0: '未处理',
    1: '处理中',
    2: '已完成',
    3: '已关闭'
  }
  
  ElMessageBox.confirm(
    `确认将该服务请求状态更改为"${statusMap[status]}"吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
    .then(async () => {
      try {
        const res = await updateServiceStatus(row.id, status)
        if (res.code === 200) {
          ElMessage.success('状态更新成功')
          loadServiceList()
        } else {
          ElMessage.error(res.message || '状态更新失败')
        }
      } catch (error) {
        console.error('更新服务请求状态出错', error)
        ElMessage.error('状态更新失败，请稍后重试')
      }
    })
    .catch(() => {
      // 取消操作
    })
}

// 打开回复对话框
const openReplyDialog = (row) => {
  currentService.value = row
  replyContent.value = row.reply || ''
  replyDialogVisible.value = true
}

// 提交回复
const submitReply = async () => {
  if (!replyContent.value.trim()) {
    ElMessage.warning('请输入回复内容')
    return
  }
  
  try {
    const res = await replyToService(currentService.value.id, replyContent.value)
    if (res.code === 200) {
      ElMessage.success('回复成功')
      replyDialogVisible.value = false
      loadServiceList()
    } else {
      ElMessage.error(res.message || '回复失败')
    }
  } catch (error) {
    console.error('回复服务请求出错', error)
    ElMessage.error('回复失败，请稍后重试')
  }
}

// 格式化服务请求类型
const formatType = (type) => {
  const typeMap = {
    0: '报修',
    1: '投诉',
    2: '生活'
  }
  return typeMap[type] || '未知'
}

// 格式化服务请求状态
const formatStatus = (status) => {
  const statusMap = {
    0: '未处理',
    1: '处理中',
    2: '已完成',
    3: '已关闭'
  }
  return statusMap[status] || '未知'
}

// 格式化图片显示
const formatImages = (images) => {
  if (!images) return ''
  
  // 处理图片数据
  let imageArray = images
  if (typeof images === 'string') {
    // 先尝试以逗号分割
    if (images.includes(',')) {
      imageArray = images.split(',').filter(item => item.trim())
    } else {
      // 再尝试解析JSON
      try {
        imageArray = JSON.parse(images)
      } catch (e) {
        // 如果解析失败，可能是单个图片URL
        imageArray = [images]
      }
    }
  }
  
  if (!Array.isArray(imageArray)) {
    imageArray = [imageArray]
  }
  
  // 过滤掉空值
  imageArray = imageArray.filter(img => img && img.trim())
  
  if (imageArray.length === 0) return ''
  
  return imageArray.map((img, index) => 
    `<img src="${getImageUrl(img)}" 
          style="max-width: 100%; max-height: 200px; margin: 5px; border-radius: 4px; cursor: pointer;" 
          onclick="window.previewImage(${index})" />`
  ).join('')
}

// 预览图片
const handlePreviewImage = (images, index = 0) => {
  if (!images) return
  
  // 处理图片数据
  let imageArray = images
  console.log("images",images);
  
  if (typeof images === 'string') {
    // 先尝试以逗号分割
    if (images.includes(',')) {
      imageArray = images.split(',').filter(item => item.trim())
    } else {
      // 再尝试解析JSON
      try {
        imageArray = JSON.parse(images)
      } catch (e) {
        // 如果解析失败，可能是单个图片URL
        imageArray = [images]
      }
    }
  }
  
  if (!Array.isArray(imageArray)) {
    imageArray = [imageArray]
  }
  
  // 过滤掉空值
  imageArray = imageArray.filter(img => img && img.trim())
  
  if (imageArray.length === 0) return
  
  // 设置预览图片数组
  previewImages.value = imageArray.map(img => getImageUrl(img))
  previewIndex.value = index
  previewVisible.value = true
}

// 在组件挂载时添加全局预览函数
onMounted(() => {
  loadServiceList()
  window.previewImage = (index) => {
    handlePreviewImage(currentService.value?.images, index)
  }
})
</script>

<template>
  <div class="service-manage-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>服务管理</span>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item>
          <el-input
            v-model="searchForm.keyword"
            placeholder="用户/内容"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.type" placeholder="服务类型" clearable style="width: 100px;">
            <el-option label="报修" :value="0" />
            <el-option label="投诉建议" :value="1" />
            <el-option label="生活" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select v-model="searchForm.status" placeholder="状态" clearable style="width: 100px;">
            <el-option label="未处理" :value="0" />
            <el-option label="处理中" :value="1" />
            <el-option label="已完成" :value="2" />
            <el-option label="已关闭" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格区域 -->
      <el-table :data="serviceList" style="width: 100%" border>
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="username" label="用户" width="100" />
        <el-table-column prop="phone" label="联系电话" width="120" />
        <el-table-column label="类型" width="80">
          <template #default="scope">
            <el-tag :type="
              scope.row.type === 0 ? 'success' :
              scope.row.type === 1 ? 'danger' :
              scope.row.type === 2 ? 'warning' : 'info'
            ">
              {{ formatType(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="内容" min-width="180" show-overflow-tooltip />
        <el-table-column prop="address" label="服务地址" min-width="150" show-overflow-tooltip />
        <el-table-column label="图片" width="100">
          <template #default="scope">
            <div v-if="scope.row.images && scope.row.images.length > 0" class="image-preview">
              <el-image
                :src="getImageUrl(scope.row.images.split(',')[0]) || getImageUrl(scope.row.images)"
                fit="cover"
                style="width: 60px; height: 60px; cursor: pointer;"
                @click="handlePreviewImage(scope.row.images)"
              />
              <span v-if="Array.isArray(scope.row.images) && scope.row.images.length > 1" class="image-count">+{{ scope.row.images.length - 1 }}</span>
            </div>
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="提交时间" width="160" />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="
              scope.row.status === 1 ? 'info' :
              scope.row.status === 2 ? 'warning' :
              scope.row.status === 3 ? 'success' : 'primary'
            ">
              {{ formatStatus(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button
              type="info"
              size="small"
              @click="handleDetail(scope.row)"
            >
              查看
            </el-button>
            <el-dropdown split-button type="primary" size="small" @click="openReplyDialog(scope.row)">
              回复
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="handleStatusChange(scope.row, 0)">
                    标记为未处理
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleStatusChange(scope.row, 1)">
                    标记为处理中
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleStatusChange(scope.row, 2)">
                    标记为已完成
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleStatusChange(scope.row, 3)">
                    标记为已关闭
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>

      <!-- 表格为空时显示 -->
      <div v-if="serviceList.length === 0" class="empty-list">
        <el-empty description="暂无服务请求数据" />
      </div>

      <!-- 分页区域 -->
      <div class="pagination-container" v-if="serviceList.length > 0">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 回复对话框 -->
    <el-dialog
      v-model="replyDialogVisible"
      title="回复服务请求"
      width="600px"
    >
      <div class="service-info" v-if="currentService">
        <p><strong>用户：</strong>{{ currentService.username }}</p>
        <p><strong>联系电话：</strong>{{ currentService.phone || '无' }}</p>
        <p><strong>服务地址：</strong>{{ currentService.address || '无' }}</p>
        <p><strong>类型：</strong>{{ formatType(currentService.type) }}</p>
        <p><strong>内容：</strong>{{ currentService.content }}</p>
        <p><strong>提交时间：</strong>{{ currentService.createTime }}</p>
        <p><strong>状态：</strong>{{ formatStatus(currentService.status) }}</p>
        
        <!-- 显示用户上传的图片 -->
        <div v-if="currentService.images" class="service-images">
          <p><strong>用户上传的图片：</strong></p>
          <div class="image-list">
            <template v-if="Array.isArray(currentService.images)">
              <div 
                v-for="(image, index) in currentService.images" 
                :key="index" 
                class="image-item"
                @click="handlePreviewImage(currentService.images, index)"
              >
                <el-image 
                  :src="getImageUrl(image)" 
                  fit="cover"
                  class="thumbnail" 
                />
              </div>
            </template>
            <template v-else-if="typeof currentService.images === 'string' && currentService.images.includes(',')">
              <!-- 处理逗号分隔的图片字符串 -->
              <div 
                v-for="(image, index) in currentService.images.split(',').filter(item => item.trim())" 
                :key="index" 
                class="image-item"
                @click="handlePreviewImage(currentService.images, index)"
              >
                <el-image 
                  :src="getImageUrl(image)" 
                  fit="cover"
                  class="thumbnail" 
                />
              </div>
            </template>
            <template v-else>
              <div 
                class="image-item"
                @click="handlePreviewImage(currentService.images)"
              >
                <el-image 
                  :src="getImageUrl(currentService.images)" 
                  fit="cover"
                  class="thumbnail" 
                />
              </div>
            </template>
          </div>
        </div>
      </div>
      <el-form>
        <el-form-item label="回复内容">
          <el-input
            v-model="replyContent"
            type="textarea"
            :rows="4"
            placeholder="请输入回复内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="replyDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitReply">提交回复</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 图片预览 -->
    <el-image-viewer
      v-if="previewVisible"
      :url-list="previewImages"
      :initial-index="previewIndex"
      @close="previewVisible = false"
    />
  </div>
</template>

<style scoped>
.service-manage-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.service-info {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.service-images {
  margin-top: 10px;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.image-item {
  width: 100px;
  height: 100px;
  cursor: pointer;
  border-radius: 4px;
  overflow: hidden;
}

.thumbnail {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-preview {
  position: relative;
}

.image-count {
  position: absolute;
  right: 2px;
  bottom: 2px;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  font-size: 12px;
  padding: 2px 4px;
  border-radius: 4px;
}

.empty-list {
  margin: 20px 0;
  display: flex;
  justify-content: center;
}
</style> 